<?php
/**
 * BootAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using BootAdmin.
 *
 * @Author G.r<root@BootAdmin.com>
 */

declare (strict_types=1);

namespace app\common\validate;

use app\common\traits\JumpTrait;
use think\Validate;

class BaseValidate extends Validate
{
    use JumpTrait;

    /**
     * 请求方式
     * @var string
     */
    public string $method = 'GET';

    /**
     * 设置请求方式
     */
    public function post()
    {
        if (!$this->request->isPost()) {
            $this->throw('请求方式错误，请使用post请求方式');
        }
        $this->method = 'POST';
        return $this;
    }

    /**
     * 设置请求方式
     */
    public function get()
    {
        if (!$this->request->isGet()) {
            $this->throw('请求方式错误，请使用get请求方式');
        }
        return $this;
    }

    /**
     * 直接获取数据
     * @return array|mixed
     */
    public function go()
    {
        //接收参数
        if ($this->method == 'GET') {
            if (!$this->request->isGet()) {
                $this->throw('请求方式错误，请使用get请求方式');
            }
            $params = request()->get();
        } else {
            if (!$this->request->isPost()) {
                $this->throw('请求方式错误，请使用post请求方式');
            }
            $params = request()->post();
        }
        return $params;
    }


    /**
     * 切面验证接收到的参数
     * @param null $scene 场景验证
     * @param array $validate_data 验证参数，可追加和覆盖掉接收的参数
     * @return array
     */
    public function goCheck($scene = null, array $validate_data = []): array
    {
        //接收参数
        $params = $this->go();
        //合并验证参数
        $params = array_merge($params, $validate_data);

        //场景
        if ($scene) {
            $result = $this->scene($scene)->check($params);
        } else {
            $result = $this->check($params);
        }

        if (!$result) {
            $exception = is_array($this->error) ? implode(';', $this->error) : $this->error;
            $this->throw($exception);
        }
        // 3.成功返回数据
        return $params;
    }

    /**
     * 字段修改场景
     * @return BaseValidate
     */
    public function sceneModify()
    {
        return $this->only(['id','field','value'])
            ->append('field', 'require')
            ->append('value', 'require');
    }
}